<template>

  <v-container class="custom-container" v-touch="{
      left: () => tabsSwitch('left'),
      right: () => tabsSwitch('right'),
    }">

    <xy-header-top title='统计报表'>
      <v-btn icon slot="left" small @click="routerBack">
        <v-icon class="white--text">iconfont-icon iconleft</v-icon>
      </v-btn>
    </xy-header-top>

    <v-tabs grow ref="tab">
      <v-tabs-slider style="color:#ff9859;"></v-tabs-slider>
      <v-tab to="/storeReportTabTotalInventory" ref="tabOne" active-class='custom-text'>库存统计</v-tab>
      <v-tab to="/storeReportTabIntoInventory" ref="tabSec" active-class='custom-text'>入库统计</v-tab>
      <v-tab to="/storeReportTabInventoryTrace" ref="tabThird" active-class='custom-text'>出库统计</v-tab>
    </v-tabs>

    <keep-alive>
      <router-view></router-view>
    </keep-alive>

    <div>
      <ul class="clearfix">
        <li>物料</li>
        <li @click="getSort('auditQuantitySort')">库存</li>
        <li>入库</li>
        <li @click="getSort('traceQuantitySort')">出库</li>
      </ul>
    </div>

    <div class="scrollWrapper" ref="scrollWrapper">

      <table class="custom-table" cellspacing=0>
        <tbody>
        <tr v-if="isRefresh">
          <td colspan="4">正在刷新...</td>
        </tr>
        <tr v-for="(item,index) in tableData" :key="index" @click="goDetail(item)">
          <td style="width:25%">{{ item.materialName }}</td>
          <td style="width:25%">{{ item.auditQuantity }}</td>
          <td style="width:25%">{{ item.auditQuantity+item.traceQuantity }}</td>
          <td style="width:25%" class="arrowRight">{{ item.traceQuantity }}</td>
        </tr>
        <tr v-if="isLoading">
          <td colspan="4">正在加载...</td>
        </tr>
        <tr v-if="noMoreData">
          <td colspan="4">没有更多数据了</td>
        </tr>

        </tbody>

      </table>

    </div>

    <!-- 日期选择组件 -->
    <xy-date-range-picker :isShowDateRangePicker="isShowDateRangePicker"
                          v-on:fromChildTurnDialogOff="handlerChildDatePickerEmit">
    </xy-date-range-picker>

    <!-- 最初版本就选择日期功能 -->
    <v-btn class="pickDateBtn" fab @click="changeDateHandel()">
      <v-icon>iconfont-icon iconrili</v-icon>
    </v-btn>

    <!-- 功能选择悬浮球 -->
    <!-- <v-speed-dial v-model="speedDial" direction="top" transition="slide-y-reverse-transition" absolute bottom right>
      <template v-slot:activator>
        <v-btn v-model="speedDial" :color="dataRange.color" dark fab>{{dataRange.text}}</v-btn>
      </template>
      <v-btn class="fs-12" fab dark small v-for="(item,index) in dateOptions" :key="index" :color="item.color"
        @click="changeDateHandel(item)">{{item.text}}
      </v-btn>
    </v-speed-dial> -->

    <!-- 分类选择组件 -->
    <xy-category-picker :isShowCategoryPicker="isShowCategoryPicker"
                        v-on:fromChildTurnDialogOff="handlerChildCategoryPickerEmit" :categoryList="categoryList"
                        v-on:selectedCategory="handlerChildSelectedCategory"></xy-category-picker>

  </v-container>

</template>


<script>
    /**
     * 统计报表
     * @author Canaan
     * @date 2019/8/10 18:25.
     */
    import {mapState} from 'vuex';
    import moment from 'moment';
    import BScroll from 'better-scroll';
    import xyDateRangePicker from "../InventoryReportIndexDateRangePicker";
    import xyCategoryPicker from "../InventoryReportIndexCategoryPicker";

    export default {
        name: 'storeReportIndex',

        mounted() {

            // this.$refs.tabSec.$el.click();

            this.getHeight();

            this.customParams.storeId = this.userContext.store.id;

            this.getTableData();

            this.$store.dispatch('loadMaterialCategoryOptions', this);
            this.categoryList = this.$store.state.materialCategoryOptions.options;

            this.itemScroll = new BScroll(this.$refs.scrollWrapper, {
                startY: 0,
                startX: 0,
                scrollY: true,
                scrollX: false,
                scrollbar: false,
                click: true,
                tap: true,
                pullUpLoad: true,
                pullDownRefresh: {
                    threshold: 60, // 当下拉到超过顶部 50px 时，触发 pullingDown 事件
                    // stop: 20 // 刷新数据的过程中，回弹停留在距离顶部还有 20px 的位置
                },
            });

            this.itemScroll.on('pullingDown', () => {
                this.isRefresh = true;
                this.isLoading = false;
                this.noMoreData = false;
                this.isScrollEnd = false;
                this.customParams.pageNo = 1;
                this.tableData = [];

                this.getTableData().then(() => {
                    this.isLoading = false;
                    this.itemScroll.refresh();
                    this.itemScroll.finishPullDown();
                });
            });

            //上拉加载
            this.itemScroll.on('pullingUp', () => {

                if (this.isScrollEnd === false) {
                    this.isLoading = true;
                    this.customParams.pageNo++;

                    this.getTableData().then(() => {
                        this.isLoading = false;
                        this.itemScroll.refresh();
                        this.itemScroll.finishPullUp();
                    });

                } else {
                    this.noMoreData = true;
                }

            })

        },
        components: {
            xyDateRangePicker,
            xyCategoryPicker
        },
        props: {},

        data() {
            return {
                currrntTabIndex: 1,
                isRefresh: false,
                noMoreData: false,
                isScrollEnd: false,
                isLoading: false,
                //悬浮按钮绑定属性
                speedDial: false,
                //已选的显示在悬浮球上
                dataRange: {
                    text: "选",
                    color: "#ff9859"
                    // text: "时",
                    // color: "#e8bb83"
                },
                dateOptions: [
                    // {
                    //   text: "时",
                    //   color: "#e8bb83"
                    // },
                    // {
                    //   text: "类",
                    //   color: "#D84315"
                    // },
                    // {
                    //   text: "店",
                    //   color: "#D84315"
                    // }
                ],
                //分类
                categoryList: null,
                dateRangeArea: {
                    startTime: moment().format('YYYY-MM-DD'),
                    endTime: moment().format('YYYY-MM-DD')
                },
                //控制时间选择器的显隐
                isShowDateRangePicker: false,
                //控制物料选择器的显隐
                isShowCategoryPicker: false,
                // checkedMaterial: {},
                //请求参数
                customParams: {
                    pageNo: 1,
                    limit: 10,
                    categoryId: undefined,
                    storeId: 0,
                    startTime: moment().subtract(7, 'days').valueOf(),
                    endTime: moment().valueOf(),
                    sort: 'auditQuantitySort',
                },
                //table的数据
                tableData: [],
            }
        },

        computed: {
            ...mapState({
                options: state => state.materialCategoryOptions.options,
                loading: state => state.materialCategoryOptions.loading,
            }),
            ...mapState([
                'userContext'
            ])
        },
        methods: {
            getSort(sort) {
                // this.customParams.sort = sort;
                // this.tableData = [];
                // this.getTableData();
                // this.$message.error("排序功能未完成");
            },
            //点击table tr 跳转到详情页
            goDetail(params) {
                this.$router.push({
                    name: 'dailyMaterialInventoryReport',
                    query: {
                        materialName: params.materialName,
                        materialId: params.materialId
                    }
                });
            },
            //悬浮球
            changeDateHandel(item) {
                this.isShowDateRangePicker = true;
                // this.dataRange = item;
                // switch (item.text) {
                //   case "时":
                //     this.isShowDateRangePicker = true;
                //     break;
                //   case "类":
                //     this.isShowCategoryPicker = true;
                //     break;
                //   case "店":
                //     break;
                //   default:
                //     throw "未知的类型：" + item.text;
                // }
            },


            //从物料选择子组件中选中后传过来的物料分类
            handlerChildSelectedCategory(val) {
                // this.customParams.categoryId = val.id;
                this.customParams.pageNo = 1;
                this.noMoreData = false;
                this.tableData = [];
                this.getTableData();
            },
            //从子组件日期选择器传值方法处理函数
            handlerChildDatePickerEmit(val) { //val是个对象
                //关闭弹层
                this.isShowDateRangePicker = val.isShowDateRangePicker;
                this.noMoreData = false;
                this.customParams.pageNo = 1;
                this.isScrollEnd = false;
                if (val.beginDate && val.endDate) {
                    this.dateRangeArea.startTime = val.beginDate;
                    this.dateRangeArea.endTime = val.endDate;
                    Object.assign(this.customParams, this.dateRangeArea);
                    this.tableData = [];
                    this.getTableData();
                }
            },
            //获取table的数据
            getTableData() {
                return this.$ajax.get("report/inventory/inventory_report", {
                    params: this.customParams
                }).then(res => {
                    if (res.code !== 'ok') {
                        this.$message.error(res.msg);
                        return;
                    }
                    if (!res.data || !res.data.inventoryReportStats || res.data.inventoryReportStats.length < this.customParams.limit) {
                        this.isScrollEnd = true;
                        return;
                    }
                    for (var i = 0; i < res.data.inventoryReportStats.length; i++) {
                        this.tableData.push(res.data.inventoryReportStats[i])
                    }
                }).then(() => {
                    this.isRefresh = false;
                    this.itemScroll.refresh();
                    this.itemScroll.finishPullUp();
                    this.itemScroll.finishPullDown();
                })
            },
            //物料类别选择处理函数
            handlerChildCategoryPickerEmit(val) {
                this.isShowCategoryPicker = val.isShowCategoryPicker;
            },
            getHeight() {
                //获取手机高度
                const clientH = document.body.clientHeight;
                let salt = 0;
                if (clientH <= 568) {
                    salt = 7;
                } else if (clientH <= 667) {
                    salt = 25;
                } else if (clientH <= 736) {
                    salt = 40;
                } else if (clientH <= 812) {
                    salt = 55;
                } else if (clientH <= 1024) {
                    salt = 62;
                }
                document.getElementById("echart-wrapper").style.height = (clientH * 0.3 + salt) + 'px';
                document.getElementsByClassName("scrollWrapper")[0].style.height = (clientH * 0.3 + salt) + 'px';
            },
            //手势切换tab
            tabsSwitch(direction) {
                if (this.currrntTabIndex === 0) {
                    switch (direction) {
                        // case 'left':
                        //     this.$router.push('/tastyIndex');
                        //     break;
                        case 'right':
                            this.currrntTabIndex = 1;
                            this.$refs.tabSec.$el.click();
                            break;
                    }
                } else if (this.currrntTabIndex === 1) {
                    switch (direction) {
                        case 'left':
                            this.currrntTabIndex = 0;
                            this.$refs.tabOne.$el.click();
                            break;
                        case 'right':
                            this.currrntTabIndex = 2;
                            this.$refs.tabThird.$el.click();
                            break;
                    }
                } else {
                    switch (direction) {
                        case 'left':
                            this.currrntTabIndex = 1;
                            this.$refs.tabSec.$el.click();
                            break;
                        case 'right':
                            return;
                    }
                }
            },
            routerBack() {
                this.$router.push("/tastyIndex");
            }
        },
        watch: {
            options(val) {
                this.categoryList = val;
            },
            // userContext: {
            //   deep: true,
            //   handler(val, oldVal) {
            //     this.customParams.storeId = val.store.id;
            //     this.getEchartData().then(() => {
            //       this.renderEchart();
            //     }).then(() => {
            //       this.customParams.limit = 10;
            //       this.getTableData();
            //     });
            //   },
            // },
            dateRangeArea: {
                deep: true,
                handler(val, oldVal) {

                },
            },
            '$route.path': function (newVal, oldVal) {
                if (newVal === '/storeReportTabInventoryTrace' && oldVal === '/storeReportTabIntoInventory') {
                    this.currrntTabIndex = 2;
                } else if (newVal === '/storeReportTabTotalInventory' && oldVal === '/storeReportTabIntoInventory') {
                    this.currrntTabIndex = 0;
                } else if (newVal === '/storeReportTabIntoInventory' && oldVal === '/storeReportTabTotalInventory') {
                    this.currrntTabIndex = 1;
                } else if (newVal === '/storeReportTabIntoInventory' && oldVal === '/storeReportTabInventoryTrace') {
                    this.currrntTabIndex = 1;
                }
            }
        },
        filters: {},
        beforeDestroy() {

        }
    }

</script>

<style scoped>
  .custom-container {
    background: #f3f7fd;
    padding: 60px 0 0;
  }

  .v-list-item__title {
    margin-bottom: 10px;
    font-size: 0.8rem;
  }

  .v-item-group {
    background: #f3f7fd
  }

  .v-application p {
    margin-bottom: 0;
  }

  .v-application--is-ltr .v-tabs-bar.v-tabs-bar--is-mobile:not(.v-tabs-bar--show-arrows) > .v-slide-group__wrapper > .v-tabs-bar__content > .v-tab:first-child,
  .v-application--is-ltr .v-tabs-bar.v-tabs-bar--is-mobile:not(.v-tabs-bar--show-arrows) > .v-slide-group__wrapper > .v-tabs-bar__content > .v-tabs-slider-wrapper + .v-tab {
    margin-left: 0;
  }

  .v-tab {
    padding: 0;
    min-width: 60px;
  }


  .custom-text {
    color: #ff9859
  }


  .v-data-table td {
    text-align: center;
    height: unset !important;
    padding: 0;
    padding: 10px;
  }

  .v-data-table tr:nth-child(odd) {
    background: #f3f7fd !important;
  }


  .pd-10 {
    padding: 10px;
  }


  .mgt-10 {
    margin-top: 10px;
  }


  .pd-05 {
    padding: 5px;
  }

  /* .custom-bg {
    color: #fff !important;
    background: #ff9859 !important;
  } */

  /* .v-speed-dial--right {
    right: 16px;
  }

  .v-speed-dial--bottom {
    bottom: 16px;
  } */

  .custom-table {
    width: 100%;
    text-align: center;
    /* border: 1px solid #ddd; */
  }

  .custom-table tbody tr:nth-child(even) {
    background: #fff !important;
  }

  .custom-table th,
  .custom-table td {
    border-top: 0;
    border-left: 0;
    padding: 8px 6px;
    font-size: 14px;
  }

  .scrollWrapper {

    overflow: hidden;
    box-sizing: border-box;
    padding: 5px;
    padding-top: 0;
  }

  ul,
  li {
    padding: 5px 5px 0 !important;
    margin: 0 !important;
  }

  li {
    padding: 10px 5px !important;
    width: 25%;
    float: left;
    text-align: center !important;
    color: #fff;
    background: #ff9859;
    list-style-type: none !important;
    font-size: 14px;
  }

  .pickDateBtn {
    color: #fff;
    background: #ff9859 !important;
    position: absolute;
    bottom: 2%;
    right: 10px;
  }

  .arrowRight {
    background: url('../../../assets/img/arrow-right.png') no-repeat;
    background-size: 20px 20px;
    background-position: 94% 50%;
  }

</style>
